package com.xz.knowledgeDuplication.thread.sync;

/**
 * 不安全银行
 * @author 召
 * @date 2022-07-25 21:56:53
 */
public class UnsafeBank {

    public static void main(String[] args) {
        Account account = new Account(100, "旅游基金");
        Drawing drawing1 = new Drawing(account, 50);
        Drawing drawing2 = new Drawing(account, 100);
        new Thread(drawing1, "小明").start();
        new Thread(drawing2, "小红").start();
    }

}

/**
 * 账户
 */
class Account {

    /**
     * 余额
     */
    private int money;

    /**
     * 卡名
     */
    private String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Drawing implements Runnable {

    /**
     * 账户
     */
    private Account account;

    /**
     * 取了多少钱
     */
    private int drawingMoney;

    /**
     * 手里的钱
     */
    private int nowMoney;

    public Drawing(Account account, int drawingMoney) {
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        // synchronized锁变化的对象
        synchronized (account) {
            if (account.getMoney() - drawingMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "钱不够了,取不了");
                return;
            }
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 卡中余额
            account.setMoney(account.getMoney() - drawingMoney);
            // 手里的钱
            nowMoney = nowMoney + drawingMoney;
            System.out.println(account.getName() + "余额: " + account.getMoney());
            System.out.println(Thread.currentThread().getName() + " : " + nowMoney);
        }
    }

}